const app = getApp();
const api = require('../../utils/api');
const Page = require('../../utils/pageProxy');

Page({
    loginRequired: true,
    data: {
        navBarHeight: 0,

        showBanner: false,
        bannerList: [], //广告banner列表
        specialPageList: [], //专题广告banner列表
        categoryList: [], //分类列表
        
        displayWindowType: 'index-platform',
        displayProductList: [], //平台或店铺推荐列表
        recommendList: [], //底部推荐列表
        pageNum: 1,
        pageSize: 9,
        total: 0,
        isFinished: false, //加载结束
        noRecommend: false, //没有推荐商品

        communityRankingList: [],
    },
    onLoad(options) {
        if(wx.getStorageSync('shop')) {
            //第三方跳转过来，去查找对应店铺
            this.findStore();
        } else if(options.scene) { //读取二维码传值
            wx.setStorageSync('shopId', options.scene); //缓存店铺id
        }

        //设置微信分享功能：可分享小程序和分享朋友圈
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        
        this.getBannerList();
        this.getCategoryList();
        this.getDisplayWindowList();
        this.getRecommendList();
        this.getCommunityRankingList();
    },
    onShow() {
        // const windowInfo = wx.getWindowInfo();
        // this.setData({
        //     navBarHeight: windowInfo.statusBarHeight + 44,
        // });
        if(app.globalData.isRefreshIndex) {
            app.globalData.isRefreshIndex = false;
            this.setData({
                recommendList: [],
                pageNum: 1,
                total: 0,
                isFinished: false,
            });
            this.getBannerList();
            this.getCategoryList();
            this.getDisplayWindowList();
            this.getRecommendList();
            this.getCommunityRankingList();
        }
    },

    findStore() { //查找店铺（第三方跳转过来时）
        let params = wx.getStorageSync('shop');
        api.post(`/shop/channel?channelCode=${params.code}&channelSubCode=${params.subCode}`)
            .then(res => {
                wx.removeStorageSync('shop');
                if(res) { //如果有店铺
                    wx.setStorageSync('shopId', res); //缓存店铺id
                    //跳转分类页面
                    wx.switchTab({
                        url: '/pages/storeIndex/storeIndex',
                    });
                }
            });
    },

    getBannerList() { //获取banner列表
        api.post('/ad/ad/list?districtCode=0&moduleNo=index')
            .then(res => {
                let bannerList = [];
                let specialPageList = [];
                res.forEach(item => {
                    if(item.targetType == 4) {
                        specialPageList.push(item);
                    } else {
                        bannerList.push(item);
                    }
                });

                this.setData({
                    bannerList: bannerList,
                    specialPageList: specialPageList,
                    showBanner: true
                });
            })
            .catch(() => {
                this.setData({
                    showBanner: true
                });
            })
    },
    gotoBannerDetail(e) { //查看广告详情
        let item = e.currentTarget.dataset.item;
        let type = item.targetType;

        if(type == 1) { //跳转小程序指定页面
            wx.navigateTo({
                url: item.frontRoutePath + '&dir=1'
            });
        } else if(type == 4) { //跳转专题页面
            wx.navigateTo({
                url: '/pages/specialPage/specialPage?id=' + item.apiUrl
            });
        } else if(type == 3) { //跳转外部小程序
            let appId = item.apiUrl;
            let path = item.frontRoutePath;
            wx.navigateToMiniProgram({
                appId: appId,
                path: path,
                success: res => {
                    console.log('打开成功')
                }
            });
        } else { //默认页面或者公众号页面
            wx.navigateTo({
                url: '/pages/adsDetail/adsDetail?id=' + item.id
            });
        }
    },

    getCategoryList() { //获取分类
        api.post('/index/platform/category/list')
            .then(res => {
                this.setData({
                    categoryList: res
                });
            })
    },
    gotoCategory(e) { //查看分类商品
        let item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: `/pages/indexCategoryProduct/indexCategoryProduct?categoryId=${item.id}&categoryName=${item.categoryName}`,
        });
    },

    switchTab(e) { //切换平台或店铺推荐列表
        let type = e.currentTarget.dataset.type;
        this.setData({
            displayWindowType: type,
            displayProductList: [],
        });
        this.getDisplayWindowList();
    },
    getDisplayWindowList() { //获取平台或店铺推荐商品
        api.post(`/product/showcase/page?moduleNo=${this.data.displayWindowType}&pageNum=1&pageSize=6`)
            .then(res => {
                this.setData({
                    displayProductList: res.content,
                    noRecommend: res.total == 0 ? true : false,
                });
            })
    },
    gotoRecommend() { //查看更多推荐商品
        wx.navigateTo({
            url: '/pages/indexRecommendProduct/indexRecommendProduct?type=' + this.data.displayWindowType,
        });
    },
    getRecommendList() { //获取页面底部推荐列表
        api.post(`/product/showcase/page?moduleNo=index-bottom&pageNum=${this.data.pageNum}&pageSize=${this.data.pageSize}`)
            .then(res => {
                let list = res.content;
                let newList = [...this.data.recommendList, ...list];
                this.setData({
                    recommendList: newList,
                    total: res.total
                });

                //是否无内容标识
                if(this.data.recommendList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.recommendList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
            })
    },
    gotoProductDetail(e) { //查看商品详情
        let item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: `/pages/storeCategoryProduct/storeCategoryProduct?id=${item.skuSaleId}&shopId=${item.shopId}`,
        });
    },

    getCommunityRankingList() { //获取社区排行榜
        api.post(`/community/commonweal/page?rankingType=history`)
            .then(res => {
                this.setData({
                    communityRankingList: res.content,
                })
            })
    },

    //顶部操作栏
    gotoSearchProduct() { //搜索商品
        wx.navigateTo({
            url: '/pages/productSearch/productSearch',
        });
    },
    scanQRcode() { //扫码
        wx.scanCode({
            // onlyFromCamera: true, // 只允许从相机扫码
            scanType: ['qrCode'],
        })
        .then(data => {
            if (data.result && data.result.indexOf('{') > -1) {
                let result = JSON.parse(data.result)
                console.log(result)
                if (result.k == 'ORDER_WRITEOFF') { //签到二维码
                    this.submitWriteoff(result.v.id);
                }
            } else {
                wx.showToast({
                    title: '请扫描有效的二维码',
                    icon: 'none'
                })
            }
        })
    },
    submitWriteoff(id) { //提交扫码结果
        api.post('/order/pickup?id=' + id)
            .then(() => {
                wx.showToast({
                    title: '核销成功！',
                    icon: 'success'
                });
            })
    },

    onPullDownRefresh() {
        //下拉刷新
        this.setData({
            displayProductList: [],
            recommendList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getDisplayWindowList();
        this.getRecommendList();
    },
    onReachBottom() {
        //加载更多
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.getRecommendList();
            }, 800);
        }
    },
    onShareAppMessage() {
        return {
            title: '八桂小铺',
            desc: '八桂小铺',
            path: 'pages/index/index'// 路径，传递参数到指定页面
        }
    }
})